package com.elloe.数组.二分查找;

import org.junit.jupiter.api.Test;

/**
 * @author ElloeStudy(Sifa Zhang)
 * @create 2022-03-09 17:25
 * To: 真常应物，真常得性，常清常静，常清静矣
 */
public class BinarySearch1 {
    @Test
    public void s1(){
        // 左闭右开
        int[] nums = {-1,0,3,5,9,12};
        int target = 2, x = -1;
        int left = 0 , right = nums.length;
        while (left < right){
            int mid = left + ((right-left)>>1);
            if (nums[mid]==target){
                x = mid;  // 基线条件 ，判断循环什么时候跳出循环
                break;
            }else if (nums[mid]>target){
                right = mid;
            }else if (nums[mid]<target){
                left = mid+1;
            }
        }
        System.out.println(x);
    }

    @Test
    public void s1Test(){
        // 再次 重复写二分查找(左闭右开)
        int[] nums = {-1,0,3,5,9,12};
        int target = 2;
        int x = -1;
        int left = 0, right = nums.length;
        while (left < right){
            int mid = left + ((right-left)>>1);
            if (nums[mid]==target){
                x = mid;
                break;
            }else if(nums[mid]>target){
                right = mid;
            }else if (nums[mid]<target){
                left = mid + 1;
            }
        }
        if (x==-1){
            System.out.println(x + " 不存在nums因此返回-1");
        }else{
            System.out.println(x);
        }
    }

    @Test
    public void s3(){
        int[] nums = {-1,0,3,5,9,12};
        int target = 2;
        int x = -1;
        int left = 0, right = nums.length;
        while (left < right){
            int mid = left + ((right - left)>>1);
            if (nums[mid]==target){
                x = mid;
                break;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else if (target < nums[mid]){
                right = mid;
            }
        }
        if (x==-1){
            System.out.println(x+ " 查找不到你的数字");
        }else{
            System.out.println(x);
        }
    }
}
